/*
 * Copyright 2016 Wealth Inc. All rights reserved.
 */
 package com.wealth.order.web.controller;

import java.util.Date;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.wealth.express.entity.Express;
import com.wealth.express.service.IExpressService;
import com.wealth.merchant.entity.Merchant;
import com.wealth.merchant.service.IMerchantService;
import com.wealth.order.entity.Order;
import com.wealth.order.entity.OrderItem;
import com.wealth.order.enums.OrderStatusEnum;
import com.wealth.order.service.IOrderItemService;
import com.wealth.order.service.IOrderService;
import com.wealth.system.entity.Corporation;
import com.wealth.system.entity.User;
import com.wealth.system.service.ShiroUser;
import com.wealth.system.web.controller.BaseController;

import iaas.enums.StatusEnum;
import iaas.enums.YesOrNoEnum;
import iaas.utils.RedirectMessage;
import iaas.web.JqGridRequest;
import iaas.web.JqGridResponse;
import iaas.web.JqGridUtil;

/**
 * @author chan
 * @version 1.0
 * @since 1.0
 */
 
@Controller
@RequestMapping(value="/manage/order/merchantorder")
public class OrderController extends BaseController{

	Logger logger = Logger.getLogger(OrderController.class);
	
	@Autowired
	private IOrderService orderService;
	@Autowired
	private IOrderItemService orderItemService;
	@Autowired
	private IMerchantService merchantService;
	@Autowired
	private IExpressService expressService;
	/**
	 * 所有RequestMapping方法调用前的Model准备方法, 实现Struts2 Preparable二次部分绑定的效果,先根据form的id从数据库查出Classify对象,再把Form提交的内容绑定到该对象上。
	 * 因为仅update()方法的form中有id属性，因此仅在update时实际执行.
	 */
	@ModelAttribute
	public void init(@RequestParam(value = "id", defaultValue = "-1") Long id, Model model) {
		try{
			if (id != -1) {
				Order order = orderService.get(id);
				model.addAttribute("order", order);
			}
		}catch(Exception e){
			logger.error("初始化错误", e);
		}
	}
	
	/**
	 * 列表
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(Model model){
		Long corpid = ShiroUser.getInstance().getUser().getCorp().getId();
		model.addAttribute("corpid", corpid);
		model.addAttribute("orderStatusEnum", OrderStatusEnum.values());
		return "order/merchantorder/list";
	}
	
	
	/**
	 * 列表ajax查询数据
	 */
	@RequestMapping(value="/list",method = RequestMethod.POST)
	@ResponseBody
	public JqGridResponse getJson(Model model,JqGridRequest request) {
		try{

			//根据商户管理账号查询商户信息
			User user = ShiroUser.getInstance().getUser();
			Merchant merchant = merchantService.getMerchantByUserId(user.getId());
			
			Page<Order> page = orderService.getOrder(merchant.getId(), request, Order.class);
			
			return JqGridUtil.getJqGrirdResponse(page);
		}catch(Exception e){
			logger.error("列表错误！", e);
			return null;
		}
	}
	
	
	/**
	 * 详情
	 */
	@RequestMapping(value="/{id}",method = RequestMethod.GET)
	public String infoForm(Model model,@PathVariable("id") Long id){
		try{
			//订单信息
			Order order = orderService.get(id);
			model.addAttribute("order", order);
			//订单明细
			List<OrderItem> orderItems=orderItemService.findByOrderId(id); 
			model.addAttribute("orderItems", orderItems);
			//订单状态
			model.addAttribute("orderStatusEnum", OrderStatusEnum.values());
			
			return "order/merchantorder/info";
		}catch(Exception e){
			logger.error("详情页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	
	/**
	 * 备注
	 */
	@RequestMapping(value="/remarks/{id}",method = RequestMethod.GET)
	public String remarks(Model model,@PathVariable("id") Long id){
		try{
			//订单信息
			Order order = orderService.get(id);
			model.addAttribute("order", order);
			//订单明细
			List<OrderItem> orderItems=orderItemService.findByOrderId(id); 
			model.addAttribute("orderItems", orderItems);
			//订单状态
			model.addAttribute("orderStatusEnum", OrderStatusEnum.values());
			
			return "order/merchantorder/remarks";
		}catch(Exception e){
			logger.error("详情页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 备注
	 */
	@RequestMapping(value="/remarks",method = RequestMethod.POST)
	public String remarksFrom(Model model,Order order,RedirectAttributes redirectAttributes){
		try{
			orderService.save(order);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("备注成功"));
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("订单备注错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 创建页面
	 */
	@RequestMapping(value="/create",method = RequestMethod.GET)
	public String createForm(){
		try {
			return "order/merchantorder/create";
		} catch (Exception e) {
			logger.error("创建页面错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 创建
	 */
	@RequestMapping(value="/create",method = RequestMethod.POST)
	public String create(Model model,Order entity,RedirectAttributes redirectAttributes){
		try {
			User user = ShiroUser.getInstance().getUser();
			
			entity.setCorp(user.getCorp());
			entity.setStatus(StatusEnum.NORMAL.getValue());
			entity.setCreateTime(new Date());
			orderService.save(entity);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("创建成功"));
			return "redirect:/manage/order/merchantorder/list";
		} catch (Exception e) {
			logger.error("创建错误", e);
			return "system/500";
		}
	}
	
	/**
	 * 编辑页面
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.GET)
	public String setUpdateForm(Model model,@PathVariable("id") Long id){
		try{
			Order order = orderService.get(id);
			model.addAttribute("order", order);
			return "order/merchantorder/update";
		}catch(Exception e){
			logger.error("编辑页面错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 修改信息
	 */
	@RequestMapping(value="/update/{id}",method = RequestMethod.POST)
	public String update(@PathVariable("id") Long id,@ModelAttribute("order") Order order,RedirectAttributes redirectAttributes){
		try{
			orderService.save(order);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("编辑成功"));
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("编辑错误,id="+id, e);
			return "system/500";
		}
	}
	
	/**
	 * 删除（逻辑删除）
	 */
	@RequestMapping(value="/delete/{id}",method = RequestMethod.GET)
	public String delete(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			orderService.deleteLogical(id);
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipSuccess("删除成功"));
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("删除错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 停用
	 */
	@RequestMapping(value="/disable/{id}",method = RequestMethod.GET)
	public String disable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			orderService.updateStatus(id, StatusEnum.STOP.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("停用成功"));
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("停用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 启用
	 */
	@RequestMapping(value="/enable/{id}",method = RequestMethod.GET)
	public String enable(@PathVariable Long id,RedirectAttributes redirectAttributes){
		try{
			orderService.updateStatus(id, StatusEnum.NORMAL.getValue());
			redirectAttributes.addFlashAttribute("message", RedirectMessage.setShowTipWarning("启用成功"));
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 发货页面
	 */
	@RequestMapping(value="/send/{id}",method = RequestMethod.GET)
	public String setsend(@PathVariable Long id,Model model, RedirectAttributes redirectAttributes){
		try{
			//订单信息
			Order order = orderService.get(id);
			model.addAttribute("order", order);
			//快递信息
			List<Express> expresses=expressService.getAll();
			model.addAttribute("expresses", expresses);
			
			return "order/merchantorder/send";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	

	/**
	 * 发货
	 */
	@RequestMapping(value="/send/{id}",method = RequestMethod.POST)
	public String send(@PathVariable Long id,@ModelAttribute("order") Order order, RedirectAttributes redirectAttributes){
		try{
			orderService.send(order);
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("启用错误,id="+id,e);
			return "system/500";
		}
	}
	
	/**
	 * 批量发货
	 * 2015-10-01 by chan
	 * ----------- 参数说明 ----------
	 * ids 订单ID
	 */
	@RequestMapping(value="/batchSend",method = RequestMethod.GET)
	public String batchSend(@RequestParam String ids,RedirectAttributes redirectAttributes){
		try{
			String id[] = ids.split(",");
			for (String gid : id) {
				Long orderid = Long.parseLong(gid);
				Order order = orderService.get(orderid);
				if(order.getPaystatus()==YesOrNoEnum.YES.getValue() || order.getDeliverstatus()==YesOrNoEnum.NO.getValue()){
					order.setStatus(OrderStatusEnum.SEND.getValue());
					order.setDeliverstatus(YesOrNoEnum.YES.getValue());
					order.setDeliverTime(new Date());
					orderService.save(order);
					
				}
			}
			return "redirect:/manage/order/merchantorder/list";
		}catch(Exception e){
			logger.error("批量发货错误,ids="+ids,e);
			return "system/500"; 
		}
	}
	
	/**
	 * 打印订单页面
	 */
	@RequestMapping(value="/print/{id}", method = RequestMethod.GET)
	public String printForm(Model model,@PathVariable Long id){
		try{
			Order order = orderService.get(id);
			model.addAttribute("order", order);
			Corporation corp = ShiroUser.getInstance().getUser().getCorp();
			model.addAttribute("corp", corp);
			return "order/merchantorder/print";
		}catch(Exception e){
			logger.error("打印订单页面错误,订单id="+id, e);
			return "system/500";
		}
	}
}